package impl;

import dao.ComRun;

import java.io.*;

public class ComRunPy implements ComRun {
    private String sourceName;
    Runtime runtime = Runtime.getRuntime();
    public ComRunPy(String sourceName){
        this.sourceName=sourceName;
    }
    @Override
    public String comRun() {
        String[] commend={"cmd","/c","python", sourceName+".py","<",sourceName+".txt"};
        Process pr = null;
        try {
            pr = runtime.exec(commend, null, new File("D:\\onlineDemo"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //串联流，能够把两个流结合起来
        SequenceInputStream sis = new SequenceInputStream(pr.getErrorStream(), pr.getInputStream());
        InputStreamReader isr = null;
        try {
            isr = new InputStreamReader(sis, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        BufferedReader br = new BufferedReader(isr);

        String res=null;
        StringBuilder strb = new StringBuilder();
        while(true){
            try {
                if ((res=br.readLine())==null) break;
            } catch (IOException e) {
                e.printStackTrace();
            }
            strb.append(res+"\n");
        }
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            pr.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        pr.destroy();
        if(strb.equals(""))
            return "操作完成";
        return strb.toString();
    }
}
